<?php
// Include database connection
require_once __DIR__ . '/../config/database.php';

// Include header
require_once 'includes/header.php';

// 初始化默认值
$modules_count = 0;
$items_count = 0;
$images_count = 0;
$recent_items = [];
$error_message = null;

// Get statistics
try {
    // Create database connection
    $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
    $conn = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Count modules
    $sql = "SELECT COUNT(*) as count FROM km_cognitive_modules";
    $result = $conn->query($sql);
    $modules_count = $result->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
    
    // Count items
    $sql = "SELECT COUNT(*) as count FROM km_cognitive_items";
    $result = $conn->query($sql);
    $items_count = $result->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
    
    // Count item images - 先检查表是否存在
    try {
        $sql = "CREATE TABLE IF NOT EXISTS `km_cognitive_item_images` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `item_id` int(11) NOT NULL,
          `image_path` varchar(255) NOT NULL,
          `title` varchar(100) DEFAULT NULL,
          `description` text DEFAULT NULL,
          `is_thumbnail` tinyint(1) NOT NULL DEFAULT 0,
          `display_order` int(11) NOT NULL DEFAULT 0,
          `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
          PRIMARY KEY (`id`),
          KEY `item_id` (`item_id`),
          CONSTRAINT `fk_item_images_item_id` FOREIGN KEY (`item_id`) REFERENCES `km_cognitive_items` (`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
        $conn->query($sql);
        
        $sql = "SELECT COUNT(*) as count FROM km_cognitive_item_images";
        $result = $conn->query($sql);
        $images_count = $result->fetch(PDO::FETCH_ASSOC)['count'] ?? 0;
    } catch (Exception $imgException) {
        // 图片表相关错误，只记录不中断
        error_log("图片统计错误: " . $imgException->getMessage());
    }
    
    // Get recently updated items
    try {
        $sql = "SELECT i.name as item_name, m.name as module_name, i.updated_at
                FROM km_cognitive_items i
                JOIN km_cognitive_modules m ON i.module_id = m.id
                ORDER BY i.updated_at DESC
                LIMIT 5";
        $result = $conn->query($sql);
        if ($result) {
            while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
                $recent_items[] = $row;
            }
        }
    } catch (Exception $recentException) {
        // 最近更新相关错误，只记录不中断
        error_log("最近更新内容错误: " . $recentException->getMessage());
    }
    
} catch (Exception $e) {
    $error_message = '数据库错误: ' . $e->getMessage();
    error_log("Dashboard数据库错误: " . $e->getMessage());
}
?>

<?php if ($error_message): ?>
<div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
<?php endif; ?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">控制面板</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <a href="modules.php" class="btn btn-sm btn-outline-secondary">管理模块</a>
            <a href="items.php" class="btn btn-sm btn-outline-secondary">管理模块内容</a>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-xl-4 col-md-6 mb-4">
        <div class="card border-left-primary shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            认知模块总数</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $modules_count; ?></div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-grid-3x3-gap fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-4 col-md-6 mb-4">
        <div class="card border-left-success shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            模块内容总数</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $items_count; ?></div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-list-ul fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-4 col-md-6 mb-4">
        <div class="card border-left-info shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">图片总数
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $images_count; ?></div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-images fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mt-4">
    <div class="col-12">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                <h6 class="m-0 font-weight-bold text-primary">最近更新的模块内容</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th>内容名称</th>
                                <th>所属模块</th>
                                <th>更新时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recent_items)): ?>
                            <tr>
                                <td colspan="3" class="text-center">暂无数据</td>
                            </tr>
                            <?php else: ?>
                                <?php foreach ($recent_items as $item): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($item['item_name'] ?? '未知'); ?></td>
                                    <td><?php echo htmlspecialchars($item['module_name'] ?? '未知'); ?></td>
                                    <td><?php echo $item['updated_at'] ?? '未知'; ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-12">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">快速操作</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <a href="modules.php" class="btn btn-primary btn-block">
                            <i class="bi bi-grid-3x3-gap"></i> 管理认知模块
                        </a>
                    </div>
                    <div class="col-md-6 mb-3">
                        <a href="items.php" class="btn btn-success btn-block">
                            <i class="bi bi-list-ul"></i> 管理模块内容
                        </a>
                    </div>
                    <div class="col-md-6 mb-3">
                        <a href="images.php" class="btn btn-info btn-block">
                            <i class="bi bi-images"></i> 管理图片
                        </a>
                    </div>
                    <div class="col-md-6 mb-3">
                        <a href="../index.html" target="_blank" class="btn btn-secondary btn-block">
                            <i class="bi bi-eye"></i> 查看网站
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Include footer
require_once 'includes/footer.php';
?> 